{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from src import *\n",
    "\n",
    "from myutils import email_notify"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "today"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with RaspiLED() as led:\n",
    "    led.check()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "############\n",
    "# Freq Est #\n",
    "############\n",
    "\n",
    "sampling_rate = 20 #Hz\n",
    "\n",
    "# freq_list = np.linspace(0.1, 0.4, 61)\n",
    "# pwm_duty = None\n",
    "\n",
    "freq_list = [0.2]\n",
    "pwm_duty = np.arange(0, 101, 2).astype(int)\n",
    "# pwm_duty = [1,3,5,7,9]\n",
    "\n",
    "A = 5\n",
    "samples = 50\n",
    "repeat = 200\n",
    "\n",
    "interval = 1/sampling_rate #s\n",
    "exposure_time = 500e-6 #s, 500 us\n",
    "timeout_milisec = int(1.5*samples*interval*1e3) #ms\n",
    "\n",
    "measurement = 'DI'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "############\n",
    "# Freq Est #\n",
    "############\n",
    "\n",
    "def task(dcam: EasyDcam, alp: EasyALP4, ground_truth, led: RaspiLED=None, pwm_duty=0):\n",
    "    print(f'Current sensor temperature is {dcam.ez_temperature()}')\n",
    "    if dcam.ez_temperature() >= -30:\n",
    "        raise RuntimeError(\"qCMOS's temperature is too high.\")\n",
    "    \n",
    "    if led is not None:\n",
    "        led.turn_on(int(pwm_duty))\n",
    "\n",
    "    ground_truth = np.round(ground_truth, 5)\n",
    "    pic_time = int(1 / (sampling_rate * ground_truth) / 2 * 1e6) #us\n",
    "\n",
    "    alp.ez_load_seq([alp.ez_single_pixel(0), alp.ez_single_pixel(A)], pic_time)\n",
    "    dcam.ez_exposure_time(exposure_time)\n",
    "    dcam.ez_triggersource_masterpluse(samples, interval)\n",
    "\n",
    "    if measurement.upper() == 'SPADE':\n",
    "        dcam.ez_roi(**SPADE.ROI)\n",
    "    elif measurement.upper() == 'DI':\n",
    "        dcam.ez_roi(**DI.ROI)\n",
    "\n",
    "    raw, timestamp = [], []\n",
    "    for _ in tqdm(range(repeat)):\n",
    "        dcam.buf_alloc(samples)\n",
    "        dcam.cap_snapshot()\n",
    "\n",
    "        alp.Run()\n",
    "        sleep(1e-6)\n",
    "        dcam.cap_firetrigger()\n",
    "\n",
    "        dcam.ez_wait_capture(timeout_milisec)\n",
    "\n",
    "        dcam.cap_stop()\n",
    "        alp.Halt()\n",
    "\n",
    "        raw_, timestamp_ = [], []\n",
    "        for frame in range(samples):\n",
    "            framedata_ = dcam.ez_read_buf(frame)\n",
    "            raw_.append(framedata_[0])\n",
    "            timestamp_.append(framedata_[1])\n",
    "\n",
    "        dcam.buf_release()\n",
    "\n",
    "        raw.append(raw_)\n",
    "        timestamp.append(timestamp_)\n",
    "\n",
    "    raw = np.array(raw)\n",
    "    timestamp = np.array(timestamp)\n",
    "\n",
    "    if not os.path.exists(f'__raw__/{today}/{measurement.lower()}_{A}px'):\n",
    "        os.makedirs(f'__raw__/{today}/{measurement.lower()}_{A}px')\n",
    "\n",
    "    np.save(f'__raw__/{today}/{measurement.lower()}_{A}px/{measurement.lower()}_{A}px_f{ground_truth}_d{pwm_duty}_raw.npy', raw)\n",
    "    np.save(f'__raw__/{today}/{measurement.lower()}_{A}px/{measurement.lower()}_{A}px_f{ground_truth}_d{pwm_duty}_timestamp.npy', timestamp)\n",
    "\n",
    "\n",
    "\n",
    "@email_notify('hcnzj@qq.com')\n",
    "def main():\n",
    "    if pwm_duty is None:\n",
    "        with EasyDcam() as dcam, EasyALP4() as alp:\n",
    "            for index, f in enumerate(freq_list):\n",
    "                print(f'({index}): f{np.round(f, 5)}_d0', end=' ')\n",
    "                task(dcam, alp, f)\n",
    "    else: \n",
    "        with RaspiLED() as led, EasyDcam() as dcam, EasyALP4() as alp:\n",
    "            for f in freq_list:\n",
    "                for index, d in enumerate(pwm_duty):\n",
    "                    print(f'({index}): f{np.round(f, 5)}_d{d}', end=' ')\n",
    "                    task(dcam, alp, f, led, d)\n",
    "\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
